import React, { useEffect, useState } from 'react';
import axios from '../axios';
import userStore from '../stores/UserStore';
import { Table, Tag, Space, message } from 'antd';
import './ApplicationList.css';

const ApplicationList = () => {
  const [pets, setPets] = useState([]); // 存储宠物及其领养申请信息
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // 从 userStore 获取用户ID
    const user = userStore.getUser();
    const userId = user?.id;

    // 调用后端接口获取申请意见列表
    axios.post('/applications/findAll', { id: userId })
      .then(response => {
        console.log('后端返回的数据:', response.data); // 打印返回的数据
        if (response.data.code === 2000) {
          setPets(response.data.data);
        } else {
          setError(response.data.msg);
        }
        setLoading(false);
      })
      .catch(error => {
        console.error('Error fetching applications:', error);
        setError('加载申请意见失败');
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <div>加载中...</div>;
  }

  if (error) {
    return <div>{error}</div>;
  }

  if (!pets || pets.length === 0) {
    return <div>暂无宠物或申请信息</div>;
  }

  // 分离已审核和未审核的申请
  const reviewedApplications = [];
  const pendingApplications = [];

  pets.forEach(pet => {
    pet.adoptApplies.forEach(apply => {
      if (apply.statusId === 5) {
        pendingApplications.push({ ...apply, petName: pet.petName });
      } else {
        reviewedApplications.push({ ...apply, petName: pet.petName });
      }
    });
  });

  const columns = [
    {
      title: '申请人',
      dataIndex: 'applicantName',
      key: 'applicantName',
      // render: (text, record) => record.user ? record.user.name : '未知',
    },
    {
      title: '宠物名称',
      dataIndex: 'petName',
      key: 'petName',
    },
    {
      title: '申请日期',
      dataIndex: 'adoptDate',
      key: 'adoptDate',
    },
    {
      title: '申请理由',
      dataIndex: 'adoptReason',
      key: 'adoptReason',
    },
    {
      title: '申请状态',
      dataIndex: 'statusId',
      key: 'statusId',
      render: statusId => (
        <Tag color={statusId === 6 ? 'green' : statusId === 7 ? 'red' : 'blue'}>
          {statusId === 6 ? '意向领养人' : statusId === 7 ? '拒绝' : '未处理'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          {record.statusId === 5 && (
            <a onClick={() => handleReview(record, 6)}>同意</a>
          )}
          {record.statusId === 5 && (
            <a onClick={() => handleReview(record, 7)}>拒绝</a>
          )}
        </Space>
      ),
    },
  ];

  const handleReview = (record, statusId) => {
    console.log('record:', record); // 打印 record 的结构
    console.log('审核请求参数:', { id: record.adoptId, statusId }); // 打印请求参数
    axios.post(`/applications/${record.adoptId}/review?statusId=${statusId}`)
      .then(response => {
        if (response.data.code === 2000) {
          // 重新获取数据
          const user = userStore.getUser();
          const userId = user?.id;
          axios.post('/applications/findAll', { id: userId })
            .then(response => {
              if (response.data.code === 2000) {
                setPets(response.data.data);
                message.success(response.data.msg);
              } else {
                message.error(response.data.msg);
              }
            })
            .catch(error => {
              console.error('Error fetching applications:', error);
              message.error('加载申请意见失败');
            });
        } else {
          message.error(response.data.msg);
        }
      })
      .catch(error => {
        console.error('Error reviewing application:', error);
        message.error('审核失败');
      });
  };

  return (
    <div>
      <h2>申请意见列表</h2>
      <div>
        <h3>未审核的申请</h3>
        <Table
          columns={columns}
          dataSource={pendingApplications}
          rowKey="id"
          bordered
          pagination={{ pageSize: 5 }}
        />
      </div>
      <div>
        <h3>已审核的申请</h3>
        <Table
          columns={columns}
          dataSource={reviewedApplications}
          rowKey="id"
          bordered
          pagination={{ pageSize: 5 }}
        />
      </div>
    </div>
  );
};

export default ApplicationList;